<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		require_once('user.php');
		$this->user=new User();
		$this->load->model('run_model');
		$this->load->model('routes_model');
	}

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->load->view('header');


		$loggedIn = $this->user->logged_in();
		$loginData['isLoggedIn'] = $loggedIn;
		if($loggedIn){
			$loginData['username'] = $_SESSION['username'];
		}
		$this->load->view('login', $loginData);

		$menu['activeController'] = 'index';
		$this->load->view('menu',$menu);

		if($loggedIn){
			
			//get lastRuns
			$runs['lastRoutes'] = $this->getRuns(3);

			$this->load->view('home', $runs);
		} else {
			$this->load->view('index');
		}
		$this->load->view('footer');
	}
	
	/**
	 * returns the last x runs from a user
	 * @param int $count
	 */
	public function getRuns($count)
	{
		$allRuns = $this->run_model->getRunsFromUser($_SESSION['id']);
		$runs = array();
		$counter = 0;
		if(count($allRuns)>0) {
			foreach ($allRuns as $i => $run){
				if($counter >= $count){
					break;
				}
				$counter++;
				
				$route = $this->routes_model->getRouteByID($run->Route);
				if(!isset($route)){
					continue;
				}
				$length = $route->Length;
				$avgSpeed = $run->AvgSpeed;
				$duration = $run->Duration;
				$runInfos->date = $run->StartTime;
				$runInfos->term = $duration;
				$runInfos->route = $route->Name;
				$runInfos->routeID = $route->ID;
				$runInfos->distance = $length;
				$runs[$i] = $runInfos;
				unset($runInfos);
			}
		}
		return $runs;
	}


}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */